import 'package:flutter/material.dart';
import 'dart:convert';
import 'dart:ui';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_yres/pages/home_page.dart';
import 'package:flutter_yres/pages/car_page.dart';
import 'package:flutter_yres/pages/shop_page.dart';
import 'package:flutter_yres/pages/mine_page.dart';
import 'package:flutter_yres/tool/Toast.dart';
import 'package:flutter_yres/tool/application.dart';
import 'package:flutter_yres/tool/AppSaveInfoUtil.dart';
import 'package:flutter_yres/tool/constant.dart';
import 'package:flutter_yres/pages/event/LoginEvent.dart';
import 'package:flutter_yres/pages/login/login_page.dart';
import 'package:flutter_yres/pages/event/UserInfoEvent.dart';
import 'package:flutter_yres/tool/network/http_url.dart';
import 'package:flutter_yres/tool/network/http_method.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../pages/shop/shop_detail_page.dart';
import '../model/shop/hdk_list_model.dart';
import '../model/shop/pdd_list.model.dart';
import '../pages/shop/pdd_detail_page.dart';
import '../pages/shop/SearchGoodsList.dart';
import '../pages/shop/SearchPDDGoodsList.dart';

class IndexPage extends StatefulWidget {
  const IndexPage({Key key}) : super(key: key);

  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> with WidgetsBindingObserver {
  String token = '';
  bool isLogin = false;
  final List<BottomNavigationBarItem> bottomTabs = [
    BottomNavigationBarItem(
        icon: Image.asset('images/icon_tab_home_nomal.png',
            fit: BoxFit.cover, width: 22, height: 22),
        activeIcon: Image.asset('images/icon_tab_home_delected.png',
            fit: BoxFit.cover, width: 22, height: 22),
        title: Text('首页')),
    BottomNavigationBarItem(
        icon: Image.asset('images/icon_tab_car_nomal.png',
            fit: BoxFit.cover, width: 22, height: 22),
        activeIcon: Image.asset('images/icon_tab_car_delected.png',
            fit: BoxFit.cover, width: 22, height: 22),
        title: Text('车生活')),
    BottomNavigationBarItem(
        icon: Image.asset('images/icon_tab_shop_nomal.png',
            fit: BoxFit.cover, width: 22, height: 22),
        activeIcon: Image.asset('images/icon_tab_shop_delected.png',
            fit: BoxFit.cover, width: 22, height: 22),
        title: Text('商城')),
    BottomNavigationBarItem(
        icon: Image.asset('images/icon_tab_personal_nomal.png',
            fit: BoxFit.cover, width: 22, height: 22),
        activeIcon: Image.asset('images/icon_tab_personal_delected.png',
            fit: BoxFit.cover, width: 22, height: 22),
        title: Text('我的')),
  ];
  List<Widget> tabBodies = [HomePage(), CarPage(), ShopPage(), MinePage()];
  int currentIndex = 0;
  var currentPage;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    currentPage = tabBodies[currentIndex];
    super.initState();
    getString(TOKEN).then((value) {
      if (value == null) {
        isLogin = true;
        Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
          return new LoginPage();
        }));
      } else {
        getUserInfo(value);
      }
    });

    APPLIC.eventBus.on<LoginEvent>().listen((event) {
      getString(TOKEN).then((value) {
        isLogin = false;
        getUserInfo(value);
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  getUserInfo(String token) async {
    FormData data = new FormData.fromMap({'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetUserMsgUrl, data: data);
    Map userMap = json.decode(response.data);
    if (userMap['code'] == 1 && mounted) {
      APPLIC.userInfoMap = userMap['data'];
      APPLIC.eventBus.fire(UserInfoEvent(APPLIC.userInfoMap));
    } else {
      isLogin = true;
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new LoginPage();
      }));
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed) {
      if (ModalRoute.of(context).isCurrent) {
        getClipboardContents();
        getString(TOKEN).then((value) {
          if (value != null) {
            getUserInfo(value);
          } else {}
        });
      }
    }
  }

  /// 使用异步调用获取系统剪贴板的返回值。
  getClipboardContents() async {
    // 访问剪贴板的内容。
    ClipboardData clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
    // 剪贴板不为空时。
    if (clipboardData != null && clipboardData.text.trim() != '') {
      print('走了');
      String _name = clipboardData.text.trim();
      // 淘口令的正则表达式，能判断类似“￥123456￥”的文本。
      // if (RegExp(r'[\uffe5]+.+[\uffe5]').hasMatch(_name)) {
      // 处理淘口令的业务逻辑。
      check(_name);

      // }

    }
  }

  showNameAlert(String good_name) {
    //搜索无结果 查找名称弹框
    showDialog<Null>(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
              title: Text('您是否搜索以下内容'),
              content: Container(
                // color: white,
                child: Column(
                  children: <Widget>[
                    Container(
                      height: 20,
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: Text(
                        good_name,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(30)),
                      ),
                    ),
                    Container(
                      alignment: Alignment.center,
                      child: Row(
                        children: <Widget>[
                          Expanded(
                              flex: 1,
                              child: GestureDetector(
                                onTap: () {
                                  Toast.toast(context, msg: '搜索宝贝');
                                  Navigator.of(context).push(
                                      new MaterialPageRoute(builder: (context) {
                                    return new SearchGoodsListPage(
                                      search: good_name,
                                    );
                                  }));
                                  Clipboard.setData(ClipboardData(text: ''));
                                },
                                child: Container(
                                  width: ScreenUtil.getInstance().setWidth(90),
                                  height: ScreenUtil.getInstance().setWidth(90),
                                  child: Image.asset(
                                    'images/s_taobao.png',
                                  ),
                                ),
                              )),
                          Expanded(
                              flex: 1,
                              child: GestureDetector(
                                onTap: () {
                                  Toast.toast(context, msg: '搜索宝贝');
                                  Navigator.of(context).push(
                                      new MaterialPageRoute(builder: (context) {
                                    return new SearchPDDGoodsListPage(
                                      search: good_name,
                                    );
                                  }));
                                  Clipboard.setData(ClipboardData(text: ''));
                                },
                                child: Container(
                                  width: ScreenUtil.getInstance().setWidth(90),
                                  height: ScreenUtil.getInstance().setWidth(90),
                                  child: Image.asset(
                                    'images/s_pinduoduo.png',
                                  ),
                                ),
                              ))
                        ],
                      ),
                    )
                  ],
                ),
              ),
              actions: <Widget>[
                new FlatButton(
                  child: new Text('取消'),
                  onPressed: () {
                    Clipboard.setData(ClipboardData(text: ''));
                    Navigator.of(context).pop();
                  },
                ),
              ]);
        });
  }

  showAlert(String good_name, String good_price, String img, String good_id,
      String type) {
    //type 1 是淘宝  2是京东  3是拼多多
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          // title: Text('检测到口令'),
          content: Container(
            child: Column(
              children: <Widget>[
                CachedNetworkImage(
                  // width: ScreenUtil.getInstance().setWidth(170),
                  // height: ScreenUtil.getInstance().setWidth(170),
                  fit: BoxFit.fill,
                  imageUrl: img,
                  placeholder: (context, url) => Image.asset(
                    'images/pic_default.png',
                    fit: BoxFit.fill,
                    // width: ScreenUtil.getInstance().setWidth(170),
                    // height: ScreenUtil.getInstance().setWidth(170),
                  ),
                  errorWidget: (context, url, error) => Image.asset(
                    'images/pic_default.png',
                    // width: ScreenUtil.getInstance().setWidth(170),
                    // height: ScreenUtil.getInstance().setWidth(170),
                    fit: BoxFit.fill,
                  ),
                ),
                Container(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    good_name,
                    style:
                        TextStyle(fontSize: ScreenUtil.getInstance().setSp(30)),
                    maxLines: 2,
                  ),
                ),
                Container(
                  height: 5,
                ),
                Container(
                    alignment: Alignment.centerLeft,
                    child: Text('¥' + good_price,
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(28),
                            color: Colors.red))),
              ],
            ),
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text('取消'),
              onPressed: () {
                Navigator.of(context).pop();
                Clipboard.setData(ClipboardData(text: ''));
              },
            ),
            new FlatButton(
              // color: Colors.red,
              child: new Text(
                '查看',
                style: TextStyle(color: Colors.red),
              ),
              onPressed: () {
                if (type == '1') {
                  Navigator.of(context).pop();
                  HDKListModelData model = new HDKListModelData();
                  model.itemid = good_id;
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          //导航打开新视图
                          builder: (context) => ShopDetailPage(
                              hdkmodel: model) //打开第二个页面，并���值，传递值的名称是model
                          ));
                  Clipboard.setData(ClipboardData(text: ''));
                }
                if (type == '3') {
                  PddListModelData model = new PddListModelData();
                  model.goods_id = good_id;
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          //导航打开新视图
                          builder: (context) => PddShopDetailPage(
                              pddmodel: model) //打开第二个页面，并传值，传递值的名称是model
                          ));
                  Clipboard.setData(ClipboardData(text: ''));
                }
              },
            ),
          ],
        );
      },
    );
  }

  check(String string) async {
    if (string.contains('mobile.yangkeduo.com/goods')) {
      //拼多多
      List array = string.split("&");
      for (String s in array) {
        if (s.contains("goods_id=")) {
          List array1 = s.split("goods_id=");
          if (array1.length > 1) {
            getString(TOKEN).then((value) {
              token = value;
              if (token == null) {
              } else {
                getPDDGoodsData(array1[1].toString());
              }
            });
          }
        }
      }
    } else if (string.contains('item.m.jd.com/product')) {
    } else {
      //淘口令
      if (string != '' && string != null && string != 'null') {
        if (string.contains("https://item.taobao.com/item.htm?id=") ||
            string.contains("http://item.taobao.com/item.htm?id=")) {
          List arr = string.split('id=');
          String uuid = arr[1];
          getString(TOKEN).then((value) {
            token = value;
            if (token == null) {
            } else {
              getGoodsData(uuid, string);
            }
          });
        } else {
          getString(TOKEN).then((value) {
            token = value;
            if (token == null) {
            } else {
              getTKLData(string);
            }
          });
        }
      }
    }
  }

  getPDDGoodsData(String uuid) async {
    print({'goods_id': uuid, 'token': token});
    FormData data = new FormData.fromMap({'goods_id': uuid, 'token': token});
    Response<String> response =
        await HttpUtil().post(Api.GetPddGoodsDetailUrl, data: data);
    Map userMap = json.decode(response.data);
    print(userMap);
    if (userMap['code'] == 0) {
      if (mounted) {
        Map goods_details = userMap['data']['goods_details'];
        List bannerData = goods_details['goods_gallery_urls'];
        showAlert(
            goods_details['goods_name'],
            (goods_details['min_group_price'] / 100).toString(),
            bannerData[0],
            goods_details['goods_id'].toString(),
            '3');
      }
    }
  }

  getGoodsData(String uuid, String all) async {
    Map map = new Map();
    map['token'] = token;
    map['num_iid'] = uuid;
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.GetGoodsMsgUrl, data: data);
    Map userMap = json.decode(response.data);
    String msg = userMap['msg'];
    print(userMap);
    if (userMap['code'].toString() == '1') {
      if (mounted) {
        showAlert(userMap['data']['title'], userMap['data']['zk_final_price'],
            userMap['data']['pict_url'], userMap['data']['num_iid'], '1');
      }
    } else {
      Toast.toast(context, msg: msg);
      if (msg == '无结果') {
        if (all.contains('】')) {
          List arr = all.split('】');
          String as = arr[0].toString();
          if (as.contains('【')) {
            List arr2 = as.split('【');
            as = arr2[1].toString();
          }
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new SearchGoodsListPage(
              search: as,
            );
          }));
        } else {
          Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
            return new SearchGoodsListPage(
              search: all.toString(),
            );
          }));
        }
      }
    }
  }

  getTKLData(String all) async {
    Map map = new Map();
    map['token'] = token;
    map['tkl'] = all;
    FormData data = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.SearchTklUrl, data: data);
    Map userMap = json.decode(response.data);
    int code = userMap['code'];
    print('口令查找1');
    print(userMap);
    String msg = userMap['msg'];
    if (code == 0) {
      if (mounted) {
        Map map2 = new Map();
        map2['token'] = token;
        map2['num_iid'] = userMap['data']['num_iid'];
        print(map2);
        FormData data2 = FormData.fromMap(new Map<String, dynamic>.from(map2));
        Response<String> response2 =
            await HttpUtil().post(Api.GetGoodsMsgUrl, data: data2);
        Map userMap2 = json.decode(response2.data);
        print('口令查找2');
        print(userMap2);
        String msg2 = userMap2['msg'];
        if (userMap2['code'].toString() == '1') {
          showAlert(
              userMap2['data']['title'],
              userMap2['data']['zk_final_price'],
              userMap2['data']['pict_url'],
              userMap2['data']['num_iid'],
              '1');
        } else {
          // Toast.toast(context, msg: msg2);
          if (msg2 == '无结果') {
            if (all.contains('】')) {
              List arr = all.split('】');
              String as = arr[0].toString();
              if (as.contains('【')) {
                List arr2 = as.split('【');
                as = arr2[1].toString();
              }
              showNameAlert(as);
              // Navigator.of(context)
              //     .push(new MaterialPageRoute(builder: (context) {
              //   return new SearchGoodsListPage(
              //     search: as,
              //   );
              // }));
            } else {
              showNameAlert(all.toString());
              // Navigator.of(context)
              //     .push(new MaterialPageRoute(builder: (context) {
              //   return new SearchGoodsListPage(
              //     search: all.toString(),
              //   );
              // }));
            }
          }
        }
      }
    } else if (code == 3 || code == 104 || code == 105) {
    } else {
      // Toast.toast(context, msg: msg);
      if (all.contains('】')) {
        List arr = all.split('】');
        String as = arr[0].toString();
        if (as.contains('【')) {
          List arr2 = as.split('【');
          as = arr2[1].toString();
        }
        showNameAlert(as);
        // Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        //   return new SearchGoodsListPage(
        //     search: as,
        //   );
        // }));
      } else {
        showNameAlert(all.toString());
        // Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        //   return new SearchGoodsListPage(
        //     search: all.toString(),
        //   );
        // }));
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
        backgroundColor: Color.fromRGBO(244, 245, 245, 1),
        bottomNavigationBar: BottomNavigationBar(
          type: BottomNavigationBarType.fixed,
          currentIndex: currentIndex,
          items: bottomTabs,
          onTap: (index) {
            setState(() {
              currentIndex = index;
              currentPage = tabBodies[currentIndex];
            });
          },
        ),
        body: IndexedStack(index: currentIndex, children: tabBodies));
  }
}
